package com.zhuoyian.dl.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import android.os.Environment;
import android.text.TextUtils;

public class DownloadPathSpec {
	private final String PATH_FILE = "/HorseBrowser/file/";
	private final String PATH_IMAGE = "/HorseBrowser/image/";
	private final String PATH_VIDEO = "/HorseBrowser/video/";
	private final String PATH_APK = "/HorseBrowser/apk/";
	private final String PATH_OTHER = "/Download/";
	private final String FILE_DEFAULT_NAME = "default_name";
	private final String UTF_8 = "UTF-8";

	private String fileName;
	private String filePath;
	private String url;

	public DownloadPathSpec(String url, int dlType, boolean isNewFile) {
		if (url == null) {
			return;
		}
		this.url = new String(url);
		fileName = url.substring(url.lastIndexOf("/") + 1);
		if(!TextUtils.isEmpty(fileName)){
		fileName=fileName.replaceAll("\\?", "");
		fileName=fileName.replaceAll("\\:", "");
		}
		try {
			fileName = URLDecoder.decode(fileName, UTF_8);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		File f = new File(getSdCard(dlType));
		if (!f.exists()) {
			f.mkdirs();
		}

		if (TextUtils.isEmpty(fileName) || "null".equalsIgnoreCase(fileName)) {
			fileName = FILE_DEFAULT_NAME;
		}

		if (isNewFile) {
			fileName = newFileName(getSdCard(dlType), fileName, 1);
		}

		filePath = new File(getSdCard(dlType), fileName).getAbsolutePath();
	}

	public String getUrl() {
		return url;
	}

	public String getName() {
		return fileName;
	}

	public String getPath() {
		return filePath;
	}

	private String getSdCard(int dlType) {
		if (DownloadParameter.TYPE_FILE == dlType) {
			return getRootPath() + PATH_FILE;
		} else if (DownloadParameter.TYPE_IMAGE == dlType) {
			return getRootPath() + PATH_IMAGE;
		} else if (DownloadParameter.TYPE_VIDEO == dlType) {
			return getRootPath() + PATH_VIDEO;
		} else if (DownloadParameter.TYPE_APK == dlType) {
			return getRootPath() + PATH_APK;
		} else {
			return getRootPath() + PATH_OTHER;
		}
	}

	private String getRootPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // �ж�sd���Ƿ����
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// ��ȡ��Ŀ¼
		} else {
			sdDir = Environment.getDownloadCacheDirectory();
		}
		if (sdDir == null) {
			sdDir = Environment.getDataDirectory();
		}
		return sdDir.toString();
	}

	private String newFileName(String dir, String name, int i) {
		File ff = new File(dir, name);
		if (ff.exists()) {
			int index = fileName.lastIndexOf(".");
			StringBuffer buf = new StringBuffer(fileName.substring(0, index));
			buf.append("(").append(i).append(")")
					.append(fileName.substring(index));
			++i;
			return newFileName(dir, buf.toString(), i);
		} else {
			return name;
		}
	}

}
